/**
 * 笔记管理组件
 * Notes Manager Component
 */

class NotesManager {
  constructor() {
    this.notes = [];
    this.currentView = 'grid'; // 'grid' or 'list'
    this.selectedNotes = new Set();
    this.sortBy = 'updated_at';
    this.sortOrder = 'desc';
    this.searchQuery = '';
    this.currentTag = '';
    this.currentPage = 1;
    this.pageSize = 20;
    this.totalPages = 1;
    this.totalNotes = 0;
    
    this.init();
  }

  /**
   * 初始化笔记管理器
   */
  init() {
    this.bindEvents();
    this.loadNotes();
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 新建笔记按钮
    const newNoteBtn = document.getElementById('new-note-btn');
    if (newNoteBtn) {
      newNoteBtn.addEventListener('click', () => this.createNewNote());
    }

    // 视图切换
    const gridViewBtn = document.getElementById('notes-grid-view-btn');
    const listViewBtn = document.getElementById('notes-list-view-btn');
    
    if (gridViewBtn) {
      gridViewBtn.addEventListener('click', () => this.switchView('grid'));
    }
    if (listViewBtn) {
      listViewBtn.addEventListener('click', () => this.switchView('list'));
    }

    // 搜索
    const searchInput = document.getElementById('notes-search-input');
    if (searchInput) {
      searchInput.addEventListener('input', (e) => {
        this.searchQuery = e.target.value.toLowerCase();
        this.currentPage = 1;
        this.loadNotes();
      });
    }

    // 排序
    const sortSelect = document.getElementById('notes-sort-select');
    if (sortSelect) {
      sortSelect.addEventListener('change', (e) => {
        const [sortBy, sortOrder] = e.target.value.split('-');
        this.sortBy = sortBy;
        this.sortOrder = sortOrder;
        this.loadNotes();
      });
    }

    // 批量操作
    const selectAllBtn = document.getElementById('select-all-notes');
    const deleteSelectedBtn = document.getElementById('delete-selected-notes');
    
    if (selectAllBtn) {
      selectAllBtn.addEventListener('click', () => this.toggleSelectAll());
    }
    if (deleteSelectedBtn) {
      deleteSelectedBtn.addEventListener('click', () => this.deleteSelectedNotes());
    }
  }

  /**
   * 加载笔记列表
   */
  async loadNotes() {
    try {
      this.showLoading();
      
      const params = new URLSearchParams({
        page: this.currentPage,
        pageSize: this.pageSize,
        sortBy: this.sortBy,
        sortOrder: this.sortOrder
      });

      if (this.searchQuery) {
        params.append('search', this.searchQuery);
      }
      if (this.currentTag) {
        params.append('tag', this.currentTag);
      }

      const response = await api.get(`/notes?${params}`);
      
      this.notes = response.data || [];
      this.totalNotes = response.total || 0;
      this.totalPages = Math.ceil(this.totalNotes / this.pageSize);
      
      this.renderNotes();
      this.updatePagination();
      this.updateStats();
      
    } catch (error) {
      console.error('加载笔记失败:', error);
      notification.error('加载笔记失败 / Failed to load notes');
    } finally {
      this.hideLoading();
    }
  }

  /**
   * 渲染笔记列表
   */
  renderNotes() {
    if (this.notes.length === 0) {
      this.showEmptyState();
      return;
    }

    this.hideEmptyState();

    if (this.currentView === 'grid') {
      this.renderGridView();
    } else {
      this.renderListView();
    }
  }

  /**
   * 渲染网格视图
   */
  renderGridView() {
    const container = document.getElementById('notes-grid');
    if (!container) return;

    container.innerHTML = this.notes.map(note => {
      const preview = this.getContentPreview(note.content);
      const tags = note.tags ? note.tags.split(',').filter(tag => tag.trim()) : [];
      
      return `
        <div class="note-item bg-white rounded-lg border border-neutral-200 p-4 hover:shadow-md transition-all cursor-pointer" 
             data-id="${note.id}">
          <div class="flex items-start justify-between mb-3">
            <input type="checkbox" class="note-checkbox rounded" data-id="${note.id}">
            <div class="flex items-center gap-2">
              <button class="note-action-btn text-neutral-400 hover:text-neutral-600" 
                      data-action="edit" data-id="${note.id}" title="编辑">
                <i class="fa fa-edit"></i>
              </button>
              <button class="note-action-btn text-neutral-400 hover:text-red-500" 
                      data-action="delete" data-id="${note.id}" title="删除">
                <i class="fa fa-trash"></i>
              </button>
            </div>
          </div>
          
          <h3 class="font-semibold text-neutral-800 mb-2 line-clamp-2" title="${note.title}">
            ${note.title || '无标题'}
          </h3>
          
          <p class="text-sm text-neutral-600 mb-3 line-clamp-3">
            ${preview}
          </p>
          
          ${tags.length > 0 ? `
            <div class="flex flex-wrap gap-1 mb-3">
              ${tags.slice(0, 3).map(tag => `
                <span class="inline-block px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full">
                  ${tag.trim()}
                </span>
              `).join('')}
              ${tags.length > 3 ? `<span class="text-xs text-neutral-500">+${tags.length - 3}</span>` : ''}
            </div>
          ` : ''}
          
          <div class="flex items-center justify-between text-xs text-neutral-500">
            <span>${this.formatDate(note.updated_at)}</span>
            <span>${this.getWordCount(note.content)} 字</span>
          </div>
        </div>
      `;
    }).join('');

    this.bindNoteEvents();
  }

  /**
   * 渲染列表视图
   */
  renderListView() {
    const container = document.getElementById('notes-list');
    if (!container) return;

    const tbody = container.querySelector('tbody');
    if (!tbody) return;

    tbody.innerHTML = this.notes.map(note => {
      const preview = this.getContentPreview(note.content);
      const tags = note.tags ? note.tags.split(',').filter(tag => tag.trim()) : [];
      
      return `
        <tr class="note-item border-b border-neutral-100 hover:bg-neutral-50" data-id="${note.id}">
          <td class="p-3">
            <input type="checkbox" class="note-checkbox rounded" data-id="${note.id}">
          </td>
          <td class="p-3">
            <div>
              <h4 class="font-medium text-neutral-800 truncate">${note.title || '无标题'}</h4>
              <p class="text-sm text-neutral-600 truncate mt-1">${preview}</p>
            </div>
          </td>
          <td class="p-3">
            ${tags.length > 0 ? `
              <div class="flex flex-wrap gap-1">
                ${tags.slice(0, 2).map(tag => `
                  <span class="inline-block px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded-full">
                    ${tag.trim()}
                  </span>
                `).join('')}
                ${tags.length > 2 ? `<span class="text-xs text-neutral-500">+${tags.length - 2}</span>` : ''}
              </div>
            ` : '-'}
          </td>
          <td class="p-3 text-sm text-neutral-600">
            ${this.formatDate(note.updated_at)}
          </td>
          <td class="p-3 text-sm text-neutral-600">
            ${this.getWordCount(note.content)}
          </td>
          <td class="p-3">
            <div class="flex items-center gap-2">
              <button class="note-action-btn text-neutral-400 hover:text-neutral-600" 
                      data-action="edit" data-id="${note.id}" title="编辑">
                <i class="fa fa-edit"></i>
              </button>
              <button class="note-action-btn text-neutral-400 hover:text-red-500" 
                      data-action="delete" data-id="${note.id}" title="删除">
                <i class="fa fa-trash"></i>
              </button>
            </div>
          </td>
        </tr>
      `;
    }).join('');

    this.bindNoteEvents();
  }

  /**
   * 绑定笔记事件
   */
  bindNoteEvents() {
    // 笔记点击事件
    document.querySelectorAll('.note-item').forEach(item => {
      item.addEventListener('click', (e) => {
        // 如果点击的是复选框或操作按钮，不触发打开笔记
        if (e.target.matches('.note-checkbox, .note-action-btn, .note-action-btn *')) {
          return;
        }
        
        const noteId = item.dataset.id;
        this.openNote(noteId);
      });
    });

    // 复选框事件
    document.querySelectorAll('.note-checkbox').forEach(checkbox => {
      checkbox.addEventListener('change', (e) => {
        e.stopPropagation();
        const noteId = checkbox.dataset.id;
        
        if (checkbox.checked) {
          this.selectedNotes.add(noteId);
        } else {
          this.selectedNotes.delete(noteId);
        }
        
        this.updateSelectionUI();
      });
    });

    // 操作按钮事件
    document.querySelectorAll('.note-action-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const action = btn.dataset.action;
        const noteId = btn.dataset.id;
        
        switch (action) {
          case 'edit':
            this.openNote(noteId);
            break;
          case 'delete':
            this.deleteNote(noteId);
            break;
        }
      });
    });
  }

  /**
   * 切换视图
   */
  switchView(view) {
    this.currentView = view;
    
    const gridViewBtn = document.getElementById('notes-grid-view-btn');
    const listViewBtn = document.getElementById('notes-list-view-btn');
    const gridContainer = document.getElementById('notes-grid-container');
    const listContainer = document.getElementById('notes-list-container');

    if (view === 'grid') {
      gridViewBtn?.classList.add('bg-primary', 'text-white');
      listViewBtn?.classList.remove('bg-primary', 'text-white');
      gridContainer?.classList.remove('hidden');
      listContainer?.classList.add('hidden');
    } else {
      listViewBtn?.classList.add('bg-primary', 'text-white');
      gridViewBtn?.classList.remove('bg-primary', 'text-white');
      listContainer?.classList.remove('hidden');
      gridContainer?.classList.add('hidden');
    }

    this.renderNotes();
  }

  /**
   * 创建新笔记
   */
  createNewNote() {
    window.location.href = '/note-editor.html';
  }

  /**
   * 打开笔记
   */
  openNote(noteId) {
    window.location.href = `/note-editor.html?id=${noteId}`;
  }

  /**
   * 删除笔记
   */
  async deleteNote(noteId) {
    const note = this.notes.find(n => n.id == noteId);
    if (!note) return;

    const confirmed = confirm(`确定要删除笔记"${note.title || '无标题'}"吗？`);
    if (!confirmed) return;

    try {
      await api.delete(`/notes/${noteId}`);
      notification.success('笔记删除成功 / Note deleted successfully');
      this.loadNotes();
    } catch (error) {
      console.error('删除笔记失败:', error);
      notification.error('删除笔记失败 / Failed to delete note');
    }
  }

  /**
   * 切换全选
   */
  toggleSelectAll() {
    const allSelected = this.selectedNotes.size === this.notes.length;
    
    if (allSelected) {
      this.selectedNotes.clear();
    } else {
      this.notes.forEach(note => this.selectedNotes.add(note.id.toString()));
    }
    
    this.updateSelectionUI();
  }

  /**
   * 删除选中的笔记
   */
  async deleteSelectedNotes() {
    if (this.selectedNotes.size === 0) {
      notification.warning('请先选择要删除的笔记 / Please select notes to delete');
      return;
    }

    const confirmed = confirm(`确定要删除选中的 ${this.selectedNotes.size} 个笔记吗？`);
    if (!confirmed) return;

    try {
      const deletePromises = Array.from(this.selectedNotes).map(noteId => 
        api.delete(`/notes/${noteId}`)
      );
      
      await Promise.all(deletePromises);
      
      notification.success(`成功删除 ${this.selectedNotes.size} 个笔记 / Successfully deleted ${this.selectedNotes.size} notes`);
      this.selectedNotes.clear();
      this.loadNotes();
    } catch (error) {
      console.error('批量删除笔记失败:', error);
      notification.error('批量删除失败 / Batch delete failed');
    }
  }

  /**
   * 更新选择状态UI
   */
  updateSelectionUI() {
    // 更新复选框状态
    document.querySelectorAll('.note-checkbox').forEach(checkbox => {
      checkbox.checked = this.selectedNotes.has(checkbox.dataset.id);
    });

    // 更新全选按钮状态
    const selectAllBtn = document.getElementById('select-all-notes');
    if (selectAllBtn) {
      const allSelected = this.selectedNotes.size === this.notes.length && this.notes.length > 0;
      selectAllBtn.textContent = allSelected ? '取消全选' : '全选';
    }

    // 更新批量操作按钮状态
    const deleteSelectedBtn = document.getElementById('delete-selected-notes');
    if (deleteSelectedBtn) {
      deleteSelectedBtn.disabled = this.selectedNotes.size === 0;
      deleteSelectedBtn.textContent = `删除选中 (${this.selectedNotes.size})`;
    }
  }

  /**
   * 更新分页
   */
  updatePagination() {
    const paginationContainer = document.getElementById('notes-pagination');
    if (!paginationContainer) return;

    if (this.totalPages <= 1) {
      paginationContainer.innerHTML = '';
      return;
    }

    let paginationHTML = '';
    
    // 上一页
    paginationHTML += `
      <button class="pagination-btn ${this.currentPage === 1 ? 'disabled' : ''}" 
              data-page="${this.currentPage - 1}" ${this.currentPage === 1 ? 'disabled' : ''}>
        <i class="fa fa-chevron-left"></i>
      </button>
    `;

    // 页码
    const startPage = Math.max(1, this.currentPage - 2);
    const endPage = Math.min(this.totalPages, this.currentPage + 2);

    if (startPage > 1) {
      paginationHTML += `<button class="pagination-btn" data-page="1">1</button>`;
      if (startPage > 2) {
        paginationHTML += `<span class="pagination-ellipsis">...</span>`;
      }
    }

    for (let i = startPage; i <= endPage; i++) {
      paginationHTML += `
        <button class="pagination-btn ${i === this.currentPage ? 'active' : ''}" 
                data-page="${i}">${i}</button>
      `;
    }

    if (endPage < this.totalPages) {
      if (endPage < this.totalPages - 1) {
        paginationHTML += `<span class="pagination-ellipsis">...</span>`;
      }
      paginationHTML += `<button class="pagination-btn" data-page="${this.totalPages}">${this.totalPages}</button>`;
    }

    // 下一页
    paginationHTML += `
      <button class="pagination-btn ${this.currentPage === this.totalPages ? 'disabled' : ''}" 
              data-page="${this.currentPage + 1}" ${this.currentPage === this.totalPages ? 'disabled' : ''}>
        <i class="fa fa-chevron-right"></i>
      </button>
    `;

    paginationContainer.innerHTML = paginationHTML;

    // 绑定分页事件
    paginationContainer.querySelectorAll('.pagination-btn:not(.disabled)').forEach(btn => {
      btn.addEventListener('click', () => {
        const page = parseInt(btn.dataset.page);
        if (page && page !== this.currentPage) {
          this.currentPage = page;
          this.loadNotes();
        }
      });
    });
  }

  /**
   * 更新统计信息
   */
  updateStats() {
    const statsContainer = document.getElementById('notes-stats');
    if (statsContainer) {
      statsContainer.textContent = `共 ${this.totalNotes} 个笔记`;
    }
  }

  /**
   * 显示/隐藏状态
   */
  showEmptyState() {
    const emptyState = document.getElementById('notes-empty-state');
    const notesGrid = document.getElementById('notes-grid-container');
    const notesList = document.getElementById('notes-list-container');
    
    emptyState?.classList.remove('hidden');
    notesGrid?.classList.add('hidden');
    notesList?.classList.add('hidden');
  }

  hideEmptyState() {
    const emptyState = document.getElementById('notes-empty-state');
    emptyState?.classList.add('hidden');
  }

  showLoading() {
    const loading = document.getElementById('notes-loading');
    loading?.classList.remove('hidden');
  }

  hideLoading() {
    const loading = document.getElementById('notes-loading');
    loading?.classList.add('hidden');
  }

  /**
   * 工具函数
   */
  getContentPreview(content) {
    if (!content) return '暂无内容';
    
    // 移除HTML标签
    const textContent = content.replace(/<[^>]*>/g, '');
    return textContent.length > 100 ? textContent.substring(0, 100) + '...' : textContent;
  }

  getWordCount(content) {
    if (!content) return 0;
    
    const textContent = content.replace(/<[^>]*>/g, '');
    // 中文按字符计算，英文按单词计算
    const chineseChars = (textContent.match(/[\u4e00-\u9fa5]/g) || []).length;
    const englishWords = (textContent.match(/[a-zA-Z]+/g) || []).length;
    return chineseChars + englishWords;
  }

  formatDate(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) return '今天';
    if (days === 1) return '昨天';
    if (days < 7) return `${days}天前`;
    if (days < 30) return `${Math.floor(days / 7)}周前`;
    if (days < 365) return `${Math.floor(days / 30)}个月前`;
    return `${Math.floor(days / 365)}年前`;
  }

  /**
   * 刷新笔记列表
   */
  async refresh() {
    await this.loadNotes();
    notification.success('笔记列表已刷新 / Notes list refreshed');
  }
}

// 导出NotesManager类
window.NotesManager = NotesManager;